using CodePen.Server.SeedData;
using CodePen.Web.Filters;
using Newtonsoft.Json.Serialization;
using RuoVea.ExFilter;
using RuoVea.ExJwtBearer;
using RuoVea.ExSugar;
using RuoVea.OmiConfig;
using RuoVea.OmiConfig.Extensions;
using RuoVea.OmiLog;
using RuoVea.OmiLogin;
using RuoVea.OmiUser;
using System.Diagnostics;

namespace CodePen.Web;

/// <summary>
/// Program
/// </summary>
public class Program
{
    /// <summary>
    /// 入口
    /// </summary>
    /// <param name="args"></param>
    /// <returns></returns>
    public static async Task Main(string[] args)
    {
        var builder = WebApplication.CreateBuilder(args);

        builder.Services.AddLocalization();

        // Add services to the container.
        builder.Services.AddControllersWithViews(options => options.Filters.Add<GlobalAuthorizeFilter>())
            .AddNewtonsoftJson(options =>
            {
                //不使用驼峰命名样式
                options.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
                //设置时间格式
                options.SerializerSettings.DateFormatString = "yyyy-MM-dd HH:mm:ss";
            });

        // 从配置中获取
        builder.Services.Configure<SystemInfo>(builder.Configuration.GetSection("SystemInfo"));

        builder.Services
            .AddHttpContextSetup<AspNetUser>()
            .AddOmiConfigSetup()
            .AddOmiLogSetup()
            .AddOmiSystemSetup()
            .AddOmiLoginSetup(o =>
            {
                o.DefaultUrl = "/manage";
                o.RedirectUrl = "/manage";
                o.LoginPath = "/auth/login";
                o.Scheme = "CodePen:" + o.Scheme;
                o.ShowI18n = true;
            });

        builder.Services
            .AddSqlSugarSetup();

        builder.Services
            .AddConfigInitSetup()
            .AddLogInitSetup()
            .AddSystemInitSetup();


        builder.Services.AddInjectServiceSetup("CodePen.Server");

        builder.Services
            .AddRestfulSetup<CustomizeFilterLog>()
            .RequestActionSetup() // 注入 请求日志拦截 [执行操作日志、参数验证 ]
            .ResultSetup()
            .ExceptionSetup();

        var app = builder.Build();

        app.UseOmiLocalization();

        if (!app.Environment.IsDevelopment())
        {
            app.UseExceptionHandler("/Home/Error");
            app.UseHsts();
        }
        //app.UseStatusCodePagesWithReExecute("/Error/{0}");
        app.UseHttpsRedirection();
        app.UseStaticFiles();

        app.UseOmiLocalization();
        app.UseRouting();

        app.UseOmiLogUI()
            .UseOmiConfigUI()
            .UseOmiSystemUI()
            .UseOmiLoginUI();

        app.MapControllerRoute(name: "default", pattern: "{controller=Home}/{action=Index}/{id?}");

        // 初始化数据库表
        await Task.Run(async () =>
        {
            var _thisRepository = app.Services.GetRequiredService<ISqlSugarClient>();
            var categorys = new List<PickCategory>();
            if (!_thisRepository.IsTableExists(typeof(PickCategory)))
            {
                _thisRepository.CodeFirst.InitTables<PickCategory>();
                categorys = new CategorySeedData().HasData().ToList();
                _thisRepository.Insertable(categorys).ExecuteCommand();
            }

            if (!_thisRepository.IsTableExists(typeof(PickContent)))
            {
                _thisRepository.CodeFirst.InitTables<PickContent>();
                var data = new PickContentSeedData().HasData().ToList();
                int i = 0;
                data.ForEach(x =>
                {
                    if (i % 3 == 0)
                        x.CategoryId = categorys[0].Id;
                    else if (i % 3 == 1)
                        x.CategoryId = categorys[1].Id;
                    else 
                        x.CategoryId = categorys[2].Id;
                    i++;
                });
                _thisRepository.Insertable(data).ExecuteCommand();
            }
            // 检查命令行参数
            if (args.Contains("--open"))
            {
                var httpUrl = builder.Configuration.GetValue<string>("Url");// 设置默认监听地址
                if (string.IsNullOrEmpty(httpUrl)) return;
                builder.WebHost.UseUrls(httpUrl);
                try { Process.Start(new ProcessStartInfo(httpUrl) { UseShellExecute = true }); }
                catch { using var client = new HttpClient(); await client.GetAsync(httpUrl); }
            }
        });

        app.Run();
    }
}